import * as _ from 'lodash';
import * as fs from 'fs-extra';

import extract = require('extract-zip');

export async function extractZipTo(source: string, target: string) {
  await extract(source, { dir: target });
}

export function isZip(zipFilePath: string): boolean {

  if (!_.isString(zipFilePath)) {
    throw new Error('provided zipFilePath is not correct.');
  }
  if (!fs.pathExistsSync(zipFilePath)) {
    throw new Error(`zipFilePath: ${zipFilePath} is not exist.`);
  }

  if (fs.lstatSync(zipFilePath).isDirectory()) {
    return false;
  }

  const buffer = Buffer.alloc(4);
  const fd = fs.openSync(zipFilePath, 'r');
  
  let ret = false;

  if (fd) {

    fs.readSync(fd, buffer, 0, 4, 0);

    if (buffer && buffer.length === 4) {
      ret = (buffer[0] === 0x50 
        && buffer[1] === 0x4b 
        && (buffer[2] === 0x03 || buffer[2] === 0x05 || buffer[2] === 0x07)
        && (buffer[3] === 0x04 || buffer[3] === 0x06 || buffer[3] === 0x08)
      );
    }
    fs.closeSync(fd);
  }
  return ret;
}

// (async () => {

//   const beginTime = +new Date();

//   await extractZipTo('/Users/ellison/Desktop/node_modules.zip', '/Users/ellison/Desktop/tmp/');

//   const endTime = +new Date();
//   console.log(`共计" ${endTime - beginTime}) ms`);
// })();